package com.lebang.controller.api.task;

import com.lebang.aop.Sessionid;
import com.lebang.common.MemberLock;
import com.lebang.common.Require;
import com.lebang.common.util.JsonDataUtil;
import com.lebang.common.util.RequestUtil;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.member.LbbMemberRecord;
import com.lebang.entity.task.LbbSosoWithBLOBs;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.Status;
import com.lebang.model.enums.TaskEnableResultEnum;
import com.lebang.model.enums.buss.RecordStatus;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.enums.buss.TaskStatus;
import com.lebang.model.enums.buss.UserStatus;
import com.lebang.model.recordback.RecordPage;
import com.lebang.model.taskback.CommonCallBack;
import com.lebang.service.TaskInRedisService;
import com.lebang.service.TaskScreenshotService;
import com.lebang.service.buss.MemberRecordService;
import com.lebang.service.buss.MemberService;
import com.lebang.service.task.TaskService;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static com.lebang.service.task.impl.SosoServiceImpl.TASK_SOSO_AMOUNT;


/**
 * 模块任务
 *
 * @author weizx
 * @className ModuleApi
 * @date 2018年7月19日 下午5:40:13
 */
@RestController
public class SosoApi {

    @Autowired
    private TaskService<LbbSosoWithBLOBs> sosoService;
    @Autowired
    private MemberRecordService memberRecordService;
    @Autowired
    private MemberService memberService;

    @Autowired
    private TaskInRedisService taskInRedisService;


    /**
     * 搜搜任务详情
     *
     * @param request
     * @param response
     * @return
     * @author weizx
     * @date 2018年7月20日 下午1:51:42
     */
    @Require
    @Sessionid
    @GetMapping(value = {"/task/soso/{taskid}", "/task/Soso/{taskid}", "/member/soso/{taskid}", "/member/Soso/{taskid}"})
    public JsonData detail(@PathVariable(value = "taskid") String taskid, HttpServletRequest request,
                           HttpServletResponse response) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        try {
            String userid = requestHeaders.getUserid();
            String imei = requestHeaders.getImei();
            LbbMember member = memberService.getMemberByMemberId(userid);
            imei = imei == null ? "" : imei;
            userid = userid == null ? "" : userid;
            // 获取任务信息
            LbbSosoWithBLOBs task = sosoService.taskInfoByTaskId(taskid);

            if (task == null) { // 任务是否存在
                return Callback.fail("empty", "soso任务不存在！");
            }
            // 下架任务不能访问
            if (Status.Off.equals(task.getStatus())) { // 任务是否下架
                return Callback.fail("offline", "soso任务已下架！");
            }
            LbbMemberRecord record = memberRecordService.checkRecord(userid, taskid, TaskCategory.Soso.name());
            // 判断用户是否做过
            String userStatus = UserStatus.Allow.name();


            CommonCallBack commonCallBack = sosoService.taskDetail(task, record, member, "");

            return Callback.success("success", "已返回soso任务详情！", commonCallBack);
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }

    /**
     * 用户soso任务
     *
     * @param page
     * @param size
     * @param request
     * @param response
     * @return
     * @author weizx
     * @date 2018年7月20日 下午9:05:52
     */
    @Require
    @Sessionid
    @RequestMapping(value = {"/member/soso", "/member/Soso"}, method = {RequestMethod.GET})
    public JsonData complete(@RequestParam(value = "page", required = false) Integer page,
                             @RequestParam(value = "size", required = false) Integer size, HttpServletRequest request,
                             HttpServletResponse response) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        try {
            String userid = requestHeaders.getUserid();
            userid = userid == null ? "" : userid;
            page = (null == page) ? 1 : page;
            size = (null == size) ? 20 : size;
            RecordPage data = memberRecordService.sosoHasCompleted(userid, page, size);
            return Callback.success("success", "已返回用户soso任务列表！", data);
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }

    /**
     * 领取任务
     *
     * @param taskid
     * @param request
     * @param response
     * @return
     * @author weizx
     * @date 2018年7月20日 下午9:30:26
     */
    @Require
    @Sessionid
    @RequestMapping(value = {"/pull/soso/{taskid}", "/pull/Soso/{taskid}"}, method = {RequestMethod.POST})
    public JsonData pull(@PathVariable("taskid") String taskid, HttpServletRequest request,
                         HttpServletResponse response) {
        try {
            RequestHeaders requsetHeader = RequestUtil.getHeader(request);
            // 获取任务信息
            LbbSosoWithBLOBs task = sosoService.taskInfoByTaskId(taskid);
            if (task == null) {
                // 任务是否存在
                return Callback.fail("empty", "任务不存在！");
            }
            TaskEnableResultEnum checkResult = sosoService.checkTaskEnableDoForUser(taskid, requsetHeader.getImei(), requsetHeader.getUserid());
            if (!checkResult.equals(TaskEnableResultEnum.SUCCESS)) {
                return Callback.fail(checkResult.getStatus(), checkResult.getMsg());
            }
            // redis 里查看任务量
            int count = taskInRedisService.getTaskAmount(TASK_SOSO_AMOUNT, task.getTaskId());
            if (count <= 0) {
                return Callback.fail("out_of_stock", "亲，任务都完了，下次起早哈！");
            }
            RecordStatus statu = sosoService.pull(requsetHeader.getUserid(), task, requsetHeader, "",task.getTaskId());
            return JsonDataUtil.toJsonData(statu);
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }

    /**
     * 提交任务
     */
    @Require
    @Sessionid
    @RequestMapping(value = {"/push/soso/{taskid}", "/push/Soso/{taskid}"}, method = {RequestMethod.POST})
    @MemberLock
    public JsonData push(@PathVariable("taskid") String taskid,
                         @RequestParam(value = "images", required = false) String images, HttpServletRequest request,
                         HttpServletResponse response, Integer sex) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String userid = requestHeaders.getUserid();
        userid = userid == null ? "" : userid;
        try {

            // 获取任务信息
            LbbSosoWithBLOBs task = sosoService.taskInfoByTaskId(taskid);
            if (task == null) {
                // 任务是否存在
                return Callback.fail("empty", "任务不存在！");
            }
            // 用户是否领取
            LbbMemberRecord record = memberRecordService.checkRecord(userid, taskid, TaskCategory.Soso.name());
            if (record == null) {
                return Callback.fail("empty", "亲，您还未领取该任务！");
            }
            if (sex != null) {
                record.setSex(sex);
            }
            // 任务是否是待提交
            if (!TaskStatus.WaitSumbit.equals(record.getStatus())) {
                return Callback.fail("sorry", "亲，您已完成过该任务！");
            }
            if (!Booleans.True.equals(task.getNeedCheck())) {
                { // 无需审核提交自动发放奖励
                    List<String> id = new ArrayList<>(1);
                    id.add(record.getId().toString());
                    sosoService.examineAndVerify(id, "", "任务成功", "",1);
                    return Callback.success("sorry", "提交任务成功");
                }
            }
            // 提交任务
            RecordStatus statu = sosoService.push(userid, record, task, images, sex);
            return JsonDataUtil.toJsonData(statu);
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }

    /**
     * 重做任务
     */
    @Require
    @Sessionid
    @RequestMapping(value = {"/soso/redo"}, method = {RequestMethod.POST})
    public JsonData redo(HttpServletRequest request, String taskid) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String userid = requestHeaders.getUserid();
        userid = userid == null ? "" : userid;
        // 获取任务信息
        LbbSosoWithBLOBs task = sosoService.taskInfoByTaskId(taskid);
        if (task == null) {
            // 任务是否存在
            return Callback.fail("fail", "任务不存在！");
        }
        if (task.getRedo() == null) {
            return Callback.fail("fail", "该任务不可重做！");
        }
        if (task.getRedo() != 1) {
            return Callback.fail("fail", "该任务不可重做！");
        }
        // 用户是否领取
        LbbMemberRecord record = memberRecordService.checkRecord(userid, taskid, null);

        if (record == null) {
            return Callback.fail("fail", "亲，您还未领取该任务！");
        }
        if (record.getCategory() != TaskCategory.Common && record.getCategory() != TaskCategory.Soso) {
            return Callback.fail("empty", "只能重做搜搜任务或通用任务！");
        }
        if (!record.getStatus().equals(TaskStatus.CheckFailure)) {
            return Callback.fail("empty", "只能重做失败状态的任务！");
        }
        ///重做任务
        RecordStatus statu = sosoService.redo(userid, record, task);
        return JsonDataUtil.toJsonData(statu);
    }

    /**
     * 催审
     */
    @Require
    @Sessionid
    @RequestMapping(value = {"/soso/task"}, method = {RequestMethod.POST})
    public JsonData task(HttpServletRequest request, String taskid) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        String userid = requestHeaders.getUserid();
        userid = userid == null ? "" : userid;
        // 获取任务信息
        LbbSosoWithBLOBs task = sosoService.taskInfoByTaskId(taskid);
        if (task == null) {
            // 任务是否存在
            return Callback.fail("fail", "任务不存在！");
        }
        if (task.getAuditTime() == null) {
            return Callback.fail("fail", "催审失败!未设置审核时间！");
        }
        LbbMemberRecord record = memberRecordService.checkRecord(userid, taskid, null);
        if (!record.getStatus().equals(TaskStatus.WaitCheckout)) {
            return Callback.fail("fail", "催审失败!该任务不处于待审核状态！");
        }
        Date date = record.getCreateTime();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MINUTE, task.getAuditTime());
        if (record.getCreateTime().after(c.getTime())) {
            return Callback.fail("fail", "催审失败!催审时间未到！");
        }
        //催审
        RecordStatus statu = sosoService.urgentTask(userid, record, task);
        return JsonDataUtil.toJsonData(statu);
    }
}
